<template>
  <div class="blog-list-container">
    <!-- 主要内容区域 -->
    <div class="main-content">
      <div class="container">
        <div class="content-layout">
          <!-- 左侧栏 -->
          <div class="leftbar">
            <ad-panel />
            <hot-recommend-panel />
            <latest-activity-panel />
          </div>
          <!-- 中间文章列表 -->
          <div class="articles-section">
            <!-- 通知 + 搜索，一行展示，搜索靠右 -->
            <div class="toolbar">
              <div class="toolbar-notice">
                <u-notice-bar background="#f0f9ff" color="#0369a1" :data="noticeList" />
              </div>
              <div class="toolbar-search">
                <u-search :config="config" @submit="submit" />
              </div>
            </div>
            <div class="section-header">
              <h2 class="section-title">
                <i class="fas fa-newspaper" />
                最新文章
              </h2>
              <div class="view-options">
                <el-radio-group v-model="viewMode" size="small">
                  <el-radio-button value="list">
                    <i class="fas fa-list" />
                  </el-radio-button>
                  <el-radio-button value="grid">
                    <i class="fas fa-th" />
                  </el-radio-button>
                </el-radio-group>
              </div>
            </div>

            <!-- 文章列表 -->
            <div class="articles-list" :class="[viewMode, { 'is-loading': loading }]">
              <!-- 初始化占位内容，防止布局晃动 -->
              <!-- grid 模式下，骨架卡片直接作为 grid 子元素 -->
              <template v-if="loading && blogCardList.length === 0 && viewMode === 'grid'">
                <div v-for="n in 6" :key="n" class="skeleton-card">
                  <el-skeleton animated>
                    <template #template>
                      <!-- 封面骨架 -->
                      <el-skeleton-item variant="image" style="height: 200px; width: 100%" />
                      <!-- 内容骨架 -->
                      <div style="padding: 20px">
                        <!-- 分类标签骨架 -->
                        <el-skeleton-item
                          variant="text"
                          style="width: 30%; height: 24px; margin-bottom: 12px; border-radius: 16px"
                        />
                        <!-- 标题骨架 -->
                        <el-skeleton-item variant="h3" style="width: 80%; margin-bottom: 12px" />
                        <!-- 摘要骨架 -->
                        <el-skeleton-item variant="text" style="width: 100%; margin-bottom: 6px" />
                        <el-skeleton-item variant="text" style="width: 90%; margin-bottom: 16px" />
                        <!-- 元信息骨架 -->
                        <div
                          style="display: flex; justify-content: space-between; align-items: center"
                        >
                          <el-skeleton-item variant="text" style="width: 120px; height: 16px" />
                          <el-skeleton-item variant="text" style="width: 150px; height: 16px" />
                        </div>
                      </div>
                    </template>
                  </el-skeleton>
                </div>
              </template>
              <!-- list 模式下，需要包装层 -->
              <div
                v-if="loading && blogCardList.length === 0 && viewMode === 'list'"
                class="loading-placeholder list"
              >
                <div v-for="n in 5" :key="n" class="skeleton-card">
                  <el-skeleton animated>
                    <template #template>
                      <!-- 封面骨架 -->
                      <el-skeleton-item variant="image" style="height: 200px; width: 100%" />
                      <!-- 内容骨架 -->
                      <div style="padding: 20px">
                        <!-- 分类标签骨架 -->
                        <el-skeleton-item
                          variant="text"
                          style="width: 30%; height: 24px; margin-bottom: 12px; border-radius: 16px"
                        />
                        <!-- 标题骨架 -->
                        <el-skeleton-item variant="h3" style="width: 80%; margin-bottom: 12px" />
                        <!-- 摘要骨架 -->
                        <el-skeleton-item variant="text" style="width: 100%; margin-bottom: 6px" />
                        <el-skeleton-item variant="text" style="width: 90%; margin-bottom: 16px" />
                        <!-- 元信息骨架 -->
                        <div
                          style="display: flex; justify-content: space-between; align-items: center"
                        >
                          <el-skeleton-item variant="text" style="width: 120px; height: 16px" />
                          <el-skeleton-item variant="text" style="width: 150px; height: 16px" />
                        </div>
                      </div>
                    </template>
                  </el-skeleton>
                </div>
              </div>

              <!-- 实际文章列表 -->
              <article
                v-for="(item, index) in blogCardList"
                :key="index"
                class="article-card"
                :class="{ 'fade-in': !loading }"
                @click="item?.blogId && goToArticle(item.blogId)"
              >
                <!-- 文章封面 -->
                <div v-if="item.blogCoverImage" class="article-cover">
                  <img
                    :src="item.blogCoverImage"
                    :alt="item.blogTitle"
                    loading="lazy"
                    @error="handleImageError"
                  />
                  <div class="cover-overlay">
                    <i class="fas fa-eye" />
                  </div>
                </div>

                <!-- 文章内容 -->
                <div class="article-content">
                  <!-- 分类标签 -->
                  <div class="article-category">
                    <router-link
                      :to="{
                        name: 'blogListShow',
                        params: { categoryId: item.blogCategoryId }
                      }"
                      class="category-tag"
                      @click.stop
                    >
                      {{ item.blogCategoryName }}
                    </router-link>
                  </div>

                  <!-- 文章标题 -->
                  <h3 class="article-title">
                    {{ item.blogTitle }}
                  </h3>

                  <!-- 文章摘要 -->
                  <p class="article-summary">
                    {{ cleanTextContent(item.blogContent) }}
                  </p>

                  <!-- 文章元信息 -->
                  <div class="article-meta">
                    <div class="author-info">
                      <author-avatar
                        :size="20"
                        :avatar="item.avatar"
                        :show-hover-info="false"
                        :author-id="item.createBy"
                      />
                      <span class="author-name">{{ item.author }}</span>
                    </div>

                    <div class="article-stats">
                      <span class="stat-item">
                        <i class="fas fa-eye" />
                        {{ item.blogViews }}
                      </span>
                      <span class="stat-item">
                        <i class="fas fa-heart" />
                        {{ item.likes }}
                      </span>
                      <span class="stat-item">
                        <i class="fas fa-clock" />
                        {{ formatTime(item.createTime) }}
                      </span>
                    </div>
                  </div>
                </div>
              </article>
            </div>

            <!-- 分页 -->
            <div class="pagination-wrapper">
              <pagination
                v-if="total > 0"
                v-model:page="listQuery.pageNum"
                v-model:limit="listQuery.pageSize"
                :page-sizes="[10, 20, 50]"
                :total="total"
                @pagination="paginationChange"
              />
            </div>
          </div>

          <!-- 右侧边栏 -->
          <div class="sidebar">
            <!-- 创作按钮 -->
            <div class="create-section">
              <el-button type="primary" class="create-btn" size="large" @click="handleCreateBlog">
                <i class="fas fa-pen-fancy" />
                开始创作
              </el-button>
            </div>

            <!-- 站点概览 -->
            <div class="overview-section">
              <site-overview-panel />
            </div>

            <!-- 文章导航 -->
            <div class="nav-section">
              <article-nav-panel />
            </div>

            <!-- 作者信息 -->
            <div class="author-section">
              <author-info-panel />
            </div>
          </div>
        </div>
      </div>
    </div>

    <login-dialog ref="loginDialogRef" v-model="loginDialogVisible" />
  </div>
</template>
<script setup lang="ts">
import { pageBlogCards } from '@/api/blog';
import { BlogInfo } from '@/api/blog/types';
import AuthorAvatar from '@/components/AuthorAvatar/index.vue';
import AdPanel from '@/components/BlogList/AdPanel.vue';
import ArticleNavPanel from '@/components/BlogList/ArticleNavPanel.vue';
import AuthorInfoPanel from '@/components/BlogList/AuthorInfoPanel.vue';
import HotRecommendPanel from '@/components/BlogList/HotRecommendPanel.vue';
import LatestActivityPanel from '@/components/BlogList/LatestActivityPanel.vue';
import SiteOverviewPanel from '@/components/BlogList/SiteOverviewPanel.vue';
import Pagination from '@/components/common/pagination/index.vue';
import { useCommonStore } from '@/store/modules/common';
import { useUserStore } from '@/store/modules/user';
import { cleanTextContent } from '@/utils';
import LoginDialog from '@/views/login/components/LoginDialog.vue';
import { ElSkeleton } from 'element-plus';
import { SearchConfig, UNoticeBar, USearch } from 'undraw-ui';
import { onMounted, ref } from 'vue';
import { onBeforeRouteUpdate, useRoute, useRouter } from 'vue-router';

const router = useRouter();
const route = useRoute();
const UserStore = useUserStore();
const CommonStore = useCommonStore();
const categoryId = ref(route.params.categoryId as string);

onBeforeRouteUpdate(newRoute => {
  categoryId.value = newRoute.params.categoryId as string;
});

const config = ref<SearchConfig>({
  search: '', // 可选输入框默认值
  keywords: CommonStore.hotKeyWords || [], // 搜索框关键字滚动
  hotSearchList: ['Java', 'HTML', 'SpringBoot', 'Vue'] // top10 热门搜索 最多显示10条数据
});

const submit = (val: string) => {
  console.log(val);
  loading.value = true;
  pageBlogCards({
    ...listQuery.value,
    keyword: val
  }).then(response => {
    const anyRes: any = response;
    blogCardList.value = anyRes.data?.list || [];
    total.value = anyRes.data?.total || 0;
    loading.value = false;
  });
};

const loading = ref(false);
const listQuery = ref({
  pageNum: 1,
  pageSize: 10
});
const total = ref(0);
// 文章卡片列表
const blogCardList = ref([] as BlogInfo[]);
// 视图模式
const viewMode = ref('list');

const search = () => {
  loading.value = true;
  pageBlogCards({
    ...listQuery.value,
    categoryId: categoryId.value || ''
  }).then(response => {
    const anyRes: any = response;
    blogCardList.value = anyRes.data?.list || [];
    total.value = Number(anyRes.data?.total || 0);
    loading.value = false;
  });
};

// 初始化
onMounted(() => {
  search();
});
// ==================================滚动通知=========================================
const noticeList = ref('网站于7月18日凌晨进行维护更新，如有卡顿，请耐心等待。');
// const noticeList = ref(CommonStore.noticeList || []);

const paginationChange = ({ page, limit }: { page: number; limit: number }) => {
  listQuery.value.pageNum = page;
  listQuery.value.pageSize = limit;
  search();
};

const loginDialogRef = ref();
const loginDialogVisible = ref(false);

// 跳转到文章详情
const goToArticle = (blogId: string | number) => {
  router.push({
    name: 'blogViewShow',
    params: { blogId: String(blogId) }
  });
};

// 格式化时间
const formatTime = (time: string | Date | undefined) => {
  if (!time) return '未知时间';
  const date = new Date(time);
  const now = new Date();
  const diff = now.getTime() - date.getTime();
  const days = Math.floor(diff / (1000 * 60 * 60 * 24));

  if (days === 0) {
    return '今天';
  } else if (days === 1) {
    return '昨天';
  } else if (days < 7) {
    return `${days}天前`;
  } else if (days < 30) {
    return `${Math.floor(days / 7)}周前`;
  } else {
    return date.toLocaleDateString();
  }
};


// 处理图片加载错误
const handleImageError = (event: Event) => {
  const target = event.target as HTMLImageElement;
  target.src = '/static/img/default.jpeg';
};

const handleCreateBlog = () => {
  if (UserStore.isLogin()) {
    router.push({ path: '/blogCreate' });
  } else {
    loginDialogVisible.value = true;
  }
};
</script>

<style scoped lang="scss">
/* ==================== 主容器 ==================== */
.blog-list-container {
  width: 100%;
  max-width: 100%;
  padding: 10px 50px;
  min-height: 100vh;
  background: #f8fafc;
  box-sizing: border-box;

  .container {
    width: 100%;
    max-width: 100%;
    margin: 0 auto;
    box-sizing: border-box;
  }

  /* ==================== 主要内容区域 ==================== */
  .main-content {
    width: 100%;
    max-width: 100%;
    box-sizing: border-box;

    .content-layout {
      display: grid;
      grid-template-columns: 260px 1fr 300px; // 左中右三栏布局
      gap: 24px;
      width: 100%;
      max-width: 100%;
      box-sizing: border-box;
    }
  }

  /* ==================== 文章列表区域 ==================== */
  .articles-section {
    width: 100%;
    max-width: 100%;
    min-width: 0; // 重要：允许在 grid 中收缩，防止溢出
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    .toolbar {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;
      .toolbar-notice {
        flex: 1;
        overflow: hidden;
        margin-right: 12px; // 给搜索框留出空间
      }
      .toolbar-search {
        display: flex;
        justify-content: flex-end;
        min-width: 280px; // 确保搜索框有最小宽度
      }
    }
    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 25px;

      .section-title {
        font-size: 1.5rem;
        color: #1e293b;
        margin: 0;
        display: flex;
        align-items: center;
        gap: 0.5rem;

        i {
          color: #3b82f6;
        }
      }

      .view-options {
        :deep(.el-radio-group) {
          .el-radio-button__inner {
            border: 1px solid #e2e8f0;
            background: white;
            color: #64748b;
            padding: 8px 12px;

            &:hover {
              color: #3b82f6;
            }
          }

          .el-radio-button__orig-radio:checked + .el-radio-button__inner {
            background: #3b82f6;
            border-color: #3b82f6;
            color: white;
          }
        }
      }
    }

    /* ==================== 文章列表容器 ==================== */
    .articles-list {
      width: 100%;
      max-width: 100%;
      min-width: 0; // 重要：允许在 grid 中收缩，防止溢出
      flex-grow: 1;
      display: flex;
      flex-direction: column;
      box-sizing: border-box;

      // 列表视图模式
      &.list {
        display: flex;
        flex-direction: column;
        gap: 20px;
      }

      // 网格视图模式
      &.grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
        gap: 20px;

        // 确保所有直接子元素（包括骨架卡片）都参与 grid 布局
        > * {
          width: 100%;
          min-width: 0; // 防止 grid item 溢出
          max-width: 100%; // 防止溢出
        }

        // 响应式调整
        @media (max-width: 1200px) {
          grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
        }

        @media (max-width: 900px) {
          grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
        }

        @media (max-width: 768px) {
          grid-template-columns: 1fr; // 小屏幕时改为单列
        }
      }

      .article-card {
        background: white;
        border-radius: 12px;
        overflow: hidden;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        transition: all 0.3s ease;
        cursor: pointer;
        min-height: 400px; // 确保最小高度，防止内容变化时的晃动

        // 淡入动画
        &.fade-in {
          animation: fadeIn 0.6s ease-out;
        }

        @keyframes fadeIn {
          from {
            opacity: 0;
            transform: translateY(20px);
          }
          to {
            opacity: 1;
            transform: translateY(0);
          }
        }

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
        }

        .article-cover {
          position: relative;
          height: 200px;
          overflow: hidden;

          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            transition: transform 0.3s ease;
          }

          .cover-overlay {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            display: flex;
            align-items: center;
            justify-content: center;
            opacity: 0;
            transition: opacity 0.3s ease;

            i {
              color: white;
              font-size: 2rem;
            }
          }

          &:hover {
            img {
              transform: scale(1.05);
            }

            .cover-overlay {
              opacity: 1;
            }
          }
        }

        .article-content {
          padding: 20px;

          .article-category {
            margin-bottom: 12px;

            .category-tag {
              display: inline-block;
              background: #f1f5f9;
              color: #3b82f6;
              padding: 4px 12px;
              border-radius: 16px;
              font-size: 0.8rem;
              font-weight: 500;
              text-decoration: none;
              transition: all 0.2s ease;

              &:hover {
                background: #e2e8f0;
                color: #2563eb;
              }
            }
          }

          .article-title {
            font-size: 1.2rem;
            font-weight: 600;
            color: #1e293b;
            margin: 0 0 12px 0;
            line-height: 1.4;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            line-clamp: 2;
            overflow: hidden;
          }

          .article-summary {
            color: #64748b;
            font-size: 0.9rem;
            line-height: 1.6;
            margin: 0 0 16px 0;
            display: -webkit-box;
            -webkit-line-clamp: 3;
            -webkit-box-orient: vertical;
            line-clamp: 3;
            overflow: hidden;
          }

          .article-meta {
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 0.8rem;
            color: #94a3b8;

            .author-info {
              display: flex;
              align-items: center;
              gap: 8px;

              .author-name {
                font-weight: 500;
                color: #64748b;
              }
            }

            .article-stats {
              display: flex;
              gap: 16px;

              .stat-item {
                display: flex;
                align-items: center;
                gap: 4px;

                i {
                  font-size: 0.7rem;
                }
              }
            }
          }
        }
      }

      /* ==================== 骨架屏样式 ==================== */
      // 骨架屏容器（仅在 list 模式下使用）
      .loading-placeholder {
        display: flex;
        flex-direction: column;
        gap: 20px;
        width: 100%;
      }

      // 骨架卡片（在 grid 模式下直接作为 grid 子元素，在 list 模式下包装在 loading-placeholder 中）
      .skeleton-card {
        background: white;
        border-radius: 12px;
        overflow: hidden;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        min-height: 400px; // 与实际文章卡片保持一致，防止布局晃动
        width: 100%;
        max-width: 100%;

        // 确保 el-skeleton 组件内部的样式不影响布局
        :deep(.el-skeleton) {
          width: 100%;
          height: 100%;
        }

        :deep(.el-skeleton__item) {
          width: 100%;
          max-width: 100%;
        }
      }
    }

    .pagination-wrapper {
      margin-top: 40px;
      display: flex;
      justify-content: center;
    }
  }

  /* ==================== 左侧边栏 ==================== */
  .leftbar {
    display: flex;
    flex-direction: column;
    gap: 20px;
  }

  /* ==================== 右侧边栏 ==================== */
  .sidebar {
    display: flex;
    flex-direction: column;
    gap: 20px;

    .create-section {
      .create-btn {
        width: 100%;
        height: 50px;
        font-size: 1rem;
        font-weight: 600;
        border-radius: 8px;
        background: linear-gradient(45deg, #3b82f6, #8b5cf6);
        border: none;
        transition: all 0.3s ease;

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 8px 25px rgba(59, 130, 246, 0.4);
        }

        i {
          margin-right: 8px;
        }
      }
    }
  }
}

/* ==================== 响应式设计 ==================== */
@media (max-width: 1024px) {
  .blog-list-container {
    .main-content .content-layout {
      grid-template-columns: 1fr;
      gap: 20px;
    }

    .sidebar {
      order: 3;
    }
    .leftbar {
      order: 2;
    }
    .articles-section {
      order: 1;
    }
  }
}

@media (max-width: 768px) {
  .blog-list-container {
    .container {
      padding: 0 16px;
    }

    .articles-section {
      .articles-list.grid {
        grid-template-columns: 1fr;
      }
      .toolbar {
        grid-template-columns: 1fr;
        .toolbar-search {
          justify-content: stretch;
        }
      }
    }
  }
}
</style>
